package com.edmodo.cropper.handle;

import com.edmodo.cropper.customutils.RectF;
import com.edmodo.cropper.edge.Edge;
import com.edmodo.cropper.util.AspectRatioUtil;

public class VerticalHandleHelper extends HandleHelper {
    private Edge mEdge;

    VerticalHandleHelper(Edge edge) {
        super(null, edge);
        mEdge = edge;
    }

    @Override
    void updateCropWindow(float x, float y, float targetAspectRatio, RectF imageRect, float snapRadius) {
        mEdge.adjustCoordinate(x, y, imageRect, snapRadius, targetAspectRatio);

        float top = Edge.TOP.getCoordinate();
        float bottom = Edge.BOTTOM.getCoordinate();

        final float targetHeight = AspectRatioUtil.calculateHeight(Edge.getWidth(), targetAspectRatio);

        final float difference = targetHeight - Edge.getHeight();
        final float halfDifference = difference / 2;
        top -= halfDifference;
        bottom += halfDifference;

        Edge.TOP.setCoordinate(top);
        Edge.BOTTOM.setCoordinate(bottom);

        if (Edge.TOP.isOutsideMargin(imageRect, snapRadius)
                && !mEdge.isNewRectangleOutOfBounds(Edge.TOP, imageRect, targetAspectRatio)) {
            final float offset = Edge.TOP.snapToRect(imageRect);
            Edge.BOTTOM.offset(-offset);
            mEdge.adjustCoordinate(targetAspectRatio);
        }

        if (Edge.BOTTOM.isOutsideMargin(imageRect, snapRadius)
                && !mEdge.isNewRectangleOutOfBounds(Edge.BOTTOM, imageRect, targetAspectRatio)) {
            final float offset = Edge.BOTTOM.snapToRect(imageRect);
            Edge.TOP.offset(-offset);
            mEdge.adjustCoordinate(targetAspectRatio);
        }
    }
}
